from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from fake_useragent import UserAgent
import time, random



#验证目标元素是否存在
def iselement(driver,mark):
    flag = True
    try:
        driver.find_element_by_partial_link_text(mark)
        return flag
    except:
        flag = False
        return flag


'''
百度搜索关键词
keywords = 关键词
mark     =目标网站的标识，有熊掌号写熊掌号，没有熊掌号写网站即可不需要加http或https
view_time = 页面停留时间
deep      = 访问深度
'''
def virtual_click(keywords, mark, view_time,deep):


    print("本次搜索的关键词为:%s-----------搜索标识%s" %(str(keywords),str(mark)))

    ua = UserAgent()
    #ip =

    dx = ['1920*1080', '1680*1050', '1366*768', '1280*800', '1600*1200', '1440*1050']
    dx = random.choice(dx)
    dx = dx.split('*')
    # 打开浏览器
    options = webdriver.ChromeOptions()
    #options.add_argument('--headless')
    options.add_argument('window-size=%dx%d' % (int(dx[0]), int(dx[1])))  # 指定浏览器分辨率
    options.add_argument('blink-settings=imagesEnabled=false')
    options.add_argument('user-agent=%s' % ua.chrome)
    #options.add_argument('--proxy-server=http://%s' % ip)
    options.add_argument('disable-infobars')  # 隐藏"Chrome正在受到自动软件的控制"
    driver = webdriver.Chrome(chrome_options=options)
    driver.set_page_load_timeout(20)
    driver.set_script_timeout(20)
    try:
        driver.get("http://www.baidu.com/")
    except:
        # 记录失败ip
        print("加载页面太慢，停止加载")
        driver.execute_script("window.stop()")
        driver.close()
        driver.quit()


    nowhandle = driver.current_window_handle
    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "kw")))
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "su")))
    except:
        driver.close()
        driver.quit()


    driver.find_element_by_id("kw").send_keys(keywords)
    driver.find_element_by_id("su").click()

    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "content_left")))
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "page")))
    except:
        driver.close()
        driver.quit()

    try:
        i = 1
        while i < 11:
            time.sleep(random.randint(3, 5))
            element = iselement(driver, mark)
            if element:
                driver.find_element_by_partial_link_text(mark).click()
                # 由于发表新话题会新窗口打开，所以要指向新窗口，即发话题窗口
                allhandles = driver.window_handles
                for handle in allhandles:
                    if (handle != nowhandle):
                        driver.switch_to.window(handle)

                browse = 1
                while browse <= view_time:
                    print("访问秒数:%d" % browse)  # 输出i
                    browse += 1
                    time.sleep(1)  # 休眠1秒

                # 记录日志
                print("完成点击")
                break
            else:
                '''
                #target = driver.find_element_by_id("id_keypair")
                #driver.execute_script("arguments[0].scrollIntoView();", target)  # 拖动到可见的元素去
                
                #前三页随机打开页面
                if i <=3:
                    print("随机打开一个页面")
                    time.sleep(1)
                    id = random.randint(1, 10)
                    driver.find_element_by_xpath("//div[@id='content_left']/div[@class='result c-container ']["+str(id)+"]/h3/a").click()
                    all_hand = driver.window_handles
                    # 切换句柄
                    driver.switch_to.window(all_hand[-1])
                    time.sleep(2)
                    #关闭窗口
                    driver.close()
                    driver.switch_to.window(all_hand[0])
                    print("关闭随机打开的页面")
                    time.sleep(1)
                '''
                driver.find_element_by_css_selector('#page > a.n:nth-last-child(1)').click()
            i += 1
    except:
        driver.close()
        driver.quit()


    try:
        link_list = []
        for link in driver.find_elements_by_xpath("//a"):
            if 'javascript' not in str(link.get_attribute("href")) and 'None' not in str(
                    link.get_attribute("href")) and 'tel:' not in str(link.get_attribute("href")) and 'sms:' not in str(
                    link.get_attribute("href")):
                link_list.append(link.get_attribute('href'))

        for deep_i in range(deep):
            deep = random.choice(link_list)
            js = " window.location.href='%s'" % deep  # 可以看到是打开新的标签页 不是窗口
            driver.execute_script(js)
            time.sleep(random.randint(5, 8))


    except:
        pass

    driver.close()
    driver.switch_to.window(nowhandle)
    driver.close()
    driver.quit()


if __name__ == '__main__':
    virtual_click("python", "www.baidu.com", "10","3")




